#include "XTcpSocket.h"
#include "XLog.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>        // for exit
#include <string.h>        // for bzero
#include <stdio.h>        // for printf
#include <unistd.h> //for close

#define MAX_RECV_DATA 1024

XTcpSocket::XTcpSocket(void)
{
    // Initialize Winsock
	_sock = 0;
}


XTcpSocket::~XTcpSocket(void)
{
	if(_sock > 0) close(_sock);
}


bool  XTcpSocket::Connect(const XString& host, const int port)
{
	struct sockaddr_in server;
	bzero(&server,sizeof(server));

	_sock = socket(AF_INET , SOCK_STREAM , 0);
    if (_sock == -1) {
        XLog::error("Could not create socket. Error");
        return false;
    }
 
    inet_aton(host.c_str(),&server.sin_addr);
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
 
    //Connect to remote server
    if (connect(_sock , (struct sockaddr *)&server , sizeof(server)) < 0) {
        XLog::error("connect failed. Error");
        return false;
    }

    XLog::info("Connected...\n");

	return true;
}

int XTcpSocket::Send(const XString& data)
{
	return send(_sock, data.c_str(), data.length(), 0);
}

int XTcpSocket::Recv(XString& data, int timeout)
{
	struct timeval tv;

	tv.tv_sec = timeout;  /* 30 Secs Timeout */
	tv.tv_usec = 0;  // Not init'ing this can cause strange errors
	setsockopt(_sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv,sizeof(struct timeval));

	char buf[MAX_RECV_DATA] = {0};
	int len = recv(_sock, buf, MAX_RECV_DATA, 0);
	if(len > 0){
		data.Append(buf, MAX_RECV_DATA);
	}

	return len;
}

